package com.ht.api.call.func.impl.kf;

import com.ht.api.bean.AjaxResult;
import com.ht.api.bean.LoginBean;
import com.ht.api.call.func.IFunctionCall;
import com.ht.api.db.*;

import cn.hutool.json.JSONObject;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

/**
 * 待接待会话查询
 */
@Slf4j
public class KfSessionWaitAccpetQueryFunctionCall implements IFunctionCall {

	@Override
	public String getName() {
		return "待接待会话查询";
	}

	@Override
	public Object execute(LoginBean me, JSONObject param, AjaxResult result) {
//		// 附加1个子查询条件
//		String subSql = """
//				(
//				  type = 1
//				  or
//				  open_kfid in(
//				    SELECT relation_id FROM position_channel WHERE `status` = 1 AND in_type = 'kf_account' AND sys_deleted = 1
//						AND team_id IN (SELECT team_id FROM fan_service_team_relation WHERE `status` = 0
//						AND userid = %s AND sys_deleted = 1)
//				  )
//				)
//				""";
//		SqlParser sqlParser = param.toBean(SqlParser.class).setTable("kf_session");
//		sqlParser.where("true", String.format(subSql, me.getLoginId()));
//		DbList list = sqlParser.query(me.getDataSource());

		String sql = """
					SELECT state FROM position_channel WHERE `status` = 1 AND in_type = 'kf_account' AND sys_deleted = 1 
					AND team_id IN (SELECT team_id FROM fan_user_team_relation WHERE `status` = 0 AND userid = ? AND sys_deleted = 1)
					""";

		DbList relationList = Db.query(me.getDataSource(), sql, me.getLoginId());

		if (relationList.size() == 0) {
			return null;
		}

		List<String> states = new ArrayList<>();
		for (Entity entity : relationList) {
			states.add(entity.getStr("state"));
		}

		SqlParser sqlParser = param.toBean(SqlParser.class).setTable("kf_session");
		sqlParser.where("scene_param", "in", states);

		DbList list = sqlParser.query(me.getDataSource());
		
		Integer pageNum = sqlParser.getPageNum();
		Integer pageSize = sqlParser.getPageSize();

		// 总记录数（有分页时，才查总记录数）
		Long total = null;
		if (pageNum != null) {
			// 注意调用sql.count方法后，将会失去limit字段，从而丢失页码信息
			total = sqlParser.count(me.getDataSource());
		}

		// 翻译字典字段
		Mapper.translate(me.getDataSource(), list);

		// 构造分页对象
		DbPage dbPage = DbPage.builder()
				.pagenum(pageNum)
				.pagesize(pageSize)
				.total(total)
				.record(list)
				.build();


		return dbPage;
	}
	

}
